package com.taglab.chic.search.web;

import com.taglab.chic.search.Query;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Markus Kobler
 */
class QueryRequestParser {

  private String searchTermsParam  = "q";
  private String startPageParam    = "p";
  private String itemsPerPageParam = "c";  
  private String languageParam     = null;  
  private boolean localized        = false;
  private int defaultItemsPerPage  = 10;

  public void setSearchTermsParam(String searchTermsParam) {
    this.searchTermsParam = searchTermsParam;
  }

  public void setStartPageParam(String startPageParam) {
    this.startPageParam = startPageParam;
  }

  public void setItemsPerPageParam(String itemsPerPageParam) {
    this.itemsPerPageParam = itemsPerPageParam;
  }

  public void setLocalized(boolean localized) {
    this.localized = localized;
  }

  public void setDefaultItemsPerPage(int defaultItemsPerPage) {
    this.defaultItemsPerPage = defaultItemsPerPage;
  }

  public Query parse(HttpServletRequest request) {
    Query query = new Query(parseParam(request, searchTermsParam, ""));
    query.setStartPage(parseParamAsInt(request, startPageParam, 0));
    query.setItemsPerPage(parseParamAsInt(request, itemsPerPageParam, defaultItemsPerPage));
    query.setLanguage(parseParam(request, languageParam, null));
    if(localized) {
      query.setLanguage(request.getHeader("Accept-Language"));
    }
    return query;
  }

  private String parseParam(HttpServletRequest request, String param, String defaultValue) {
    if( param != null ) {
      String value = request.getParameter(param);
      if( value != null ) {
        return value;
      }
    }
    return defaultValue;
  }

  private int parseParamAsInt(HttpServletRequest request, String param, int defaultValue) {
    if( param != null ) {
      String value = request.getParameter(param);
      if( value != null ) {
        try {
          return Integer.parseInt(value);
        } catch( NumberFormatException ex ) {
          // ignore use default
        }
      }
    }
    return defaultValue;
  }


}
